﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
using CommandLib;
using DatabaseLib;
using SysLogLib;
using WebServerLib;
using SettLib;

// DFL's Syslog analyser service v.1.0
// by George Makarov
// Email: georgemakarov1@yandex.ru

namespace DFLSvc
{
    public partial class DFLSvc : ServiceBase
    {
        private string StartupPath;

        public cSettings Settings;

        cWebServer WebServer;
        cSysLog Syslog;
        cCommand CommandHandler;
        ConnectionConfig ConnConf;
        DB db;
        bool AppTerminate = false;
        StreamWriter Log;
        StreamWriter ErrLog;

        public DFLSvc()
        {
            InitializeComponent();
            
            StartupPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
            Log = new StreamWriter(Path.Combine(StartupPath,"log.txt"), true);
            Log.AutoFlush = true;
            ErrLog = new StreamWriter(Path.Combine(StartupPath, "errlog.txt"), true);
            ErrLog.AutoFlush = true;
            WriteToLog("Service started");
            Settings = new cSettings();
            if (!Settings.LoadSettings(Path.Combine(StartupPath,"settings.xml")))
            {
                AppTerminate = true;
                this.Stop();
            }
            WriteToLog("Settings loaded");
            if (!AppTerminate)
            {
                ConnConf = new ConnectionConfig(DatabaseTypes.typeMsSqlCE);
                ConnConf.SDFFilename = Settings.Data.Main.SDFFilename;
                db = new DB(ConnConf);
                db.ErrorHandler += ErrorHandler;
                WebServer = new cWebServer(Settings.Data.Webserver, db);
                //WebServer.ExecuteQuery += db.ExecuteQuery;
                //WebServer.GetQueryTable += db.GetQueryTable;
                WebServer.ErrorHandler += ErrorHandler;
                CommandHandler = new cCommand(WebServer, Settings, db);
                CommandHandler.LogHandler += WriteToLog;
                CommandHandler.ErrorHandler += ErrorHandler;
                WebServer.CommandHandler += CommandHandler.ExecuteCommand;
                WebServer.ErrorHandler += ErrorHandler;
                WebServer.LogHandler += WriteToLog;
                Syslog = new cSysLog(Settings.Data.Syslog, db);
                //Syslog.ExecuteQuery += db.ExecuteQuery;
                //Syslog.ExecuteQueryBatch += db.ExecuteQueryBatch;
                //Syslog.GetQueryTable += db.GetQueryTable;
                Syslog.ErrorHandler += ErrorHandler;
                Syslog.LogHandler += WriteToLog;
            }
        }

        private void WriteToLog(string aMessage)
        {
            try
            {
                Log.Write("[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "] " + aMessage + "\r\n");
            }
            catch
            { }
        }


        private void ErrorHandler(Exception ex)
        {
            try
            {
                ErrLog.Write("[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "] Message:" + ex.Message + "\r\n");
            }
            catch
            { }
        }

        protected override void OnStart(string[] args)
        {
            WebServer.Start();
            Syslog.Start();
        }

        protected override void OnStop()
        {
            if ((WebServer != null) && (WebServer.Running))
            {
                WebServer.Stop();
            }
            if ((Syslog != null) && (Syslog.Running))
            {
                Syslog.Stop();
            }
            Settings.SaveSettings(Path.Combine(StartupPath, "settings.xml"));
            WriteToLog("Settings saved");

            WriteToLog("Service Stopped");
            Log.Close();
            ErrLog.Close();
        }
    }
}
